﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Telerik.Windows.Controls;
using Telerik.Charting;

namespace IndustrialSmokeCalc
{
    public partial class History : PhoneApplicationPage
    {
        public History()
        {
            InitializeComponent();
            listHistory.SetValue(TiltEffect.IsTiltEnabledProperty, true);
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (listHistory.Items.Count == 0) busyIndicator.IsRunning = true;
            GetHistory();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            listHistory.SelectedIndex = -1;
        }

        private void GetHistory()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetMeasurementListCompleted += GetMeasurementListCompleted;
            client.GetMeasurementListAsync("history", DataSingleton.Instance.ChimneyId);
        }

        private void GetMeasurementListCompleted(object sender, GetMeasurementListCompletedEventArgs e)
        {
            busyIndicator.IsRunning = false;
            Thread.Sleep(500);
            DataSingleton.Instance.MeasurementList = e.Result;
            if (e.Result.Count == 0)
            {
                MessageBox.Show("Tidak terdapat histori pengamatan.");
            }
            else
            {
                listHistory.ItemsSource = e.Result;
                btnViewChart.Visibility = Visibility.Visible;
            }
        }

        private void listHistory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listHistory.SelectedIndex >= 0)
            {
                Measurement selectedMeasurement = listHistory.SelectedItem as Measurement;
                DataSingleton.Instance.MeasurementId = selectedMeasurement.MeasurementId;
                NavigationService.Navigate(new Uri("/MeasurementDetail.xaml", UriKind.Relative));
            }
        }

        private void btnViewChart_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Chart.xaml", UriKind.Relative));
        }
    }
}